Code of Jigsaw Puzzle
Write the object-oriented code to implement the design of the jigsaw problem.
We'll cover the following
We’ve gone over the different aspects of the jigsaw puzzle and observed the attributes attached to the problem using various UML diagrams. Let’s explore the more practical side of things, where we will work on implementing the jigsaw puzzle using multiple languages. This is usually the last step in an object-oriented design interview process.
We have chosen the following languages to write the skeleton code of the different classes present in the jigsaw puzzle:
Java
C#
Python
C++
JavaScript
Jigsaw puzzle#
In this section, we’ll provide the skeleton code of the classes designed in the class diagram lesson.
Note: For simplicity, we are not defining getter and setter functions. The reader can assume that all class attributes are private and accessed through their respective public getter methods and modified only through their public method functions.
Enumerations#
The following code defines the Edge
enum that represents the shape of the puzzle piece:
Note: JavaScript does not support enumerations, so we will be using the
Object.freeze()
method as an alternative that freezes an object and prevents further modifications.
Side #
The Side
class contains a reference to the Edge
enum that will describe the edge shape of any side of a puzzle piece. Its definition is given below:
Piece#
The Piece
class contains a list of sides (representing each side of a piece) and ensures if a particular piece is a corner, middle, or edge using its respective functions. The definition of this class is provided below:
Puzzle#
The Puzzle class includes the entire board of the jigsaw puzzle as well as the unused pieces. Since the board is a rectangle, it will be represented using a 2-D array. In addition, there will be only one instance of the puzzle board in the jigsaw puzzle. Therefore, the Puzzle class will be a Singleton class to ensure that only one instance for the board is created in the entire system. The definition of this class is given below:
Puzzle solver#
The PuzzleSolver
class tries to solve the puzzle using the matchPieces()
function. Its definition is given below:
Wrapping up#
We've explored the complete design of a jigsaw puzzle in this chapter. We've looked at how a basic jigsaw puzzle can be visualized using various UML diagrams and designed it using object-oriented principles and design patterns.
Class Diagram for the Jigsaw Puzzle
Getting Ready: The Airline Management System